package com.kpa.demo.data.http.interceptor

import com.google.gson.Gson
import com.kpa.demo.data.ApiException
import com.kpa.demo.data.model.ResultBean
import okhttp3.ResponseBody
import retrofit2.Converter
import java.lang.reflect.Type

/**
 * 接口返回数据转换
 */
class ResponseBodyConverter<T>(private val gson: Gson, private val type: Type): Converter<ResponseBody, T> {

    override fun convert(value: ResponseBody): T? {
        val response = value.source().readUtf8()
        val resultBean = gson.fromJson<ResultBean<String>>(response, ResultBean::class.java)
        if (resultBean.code == 1000) {
            return gson.fromJson<T>(response, type)
        } else {
            throw ApiException(resultBean.data)
        }
    }
}